package com.zf.shopping.service.impl;

import com.zf.shopping.bean.GetResult;
import com.zf.shopping.bean.Result;
import com.zf.shopping.dao.CategoryMapper;
import com.zf.shopping.dao.CommodityCategoryMapper;
import com.zf.shopping.model.Category;
import com.zf.shopping.model.CategoryExample;
import com.zf.shopping.model.CommodityCategory;
import com.zf.shopping.model.CommodityCategoryExample;
import com.zf.shopping.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CommodityCategoryMapper commodityCategoryMapper;

    @Override
    public Result addOrUpdate(Category category) {

        try {
            if (category.getId() == 0 || category.getId() == null) {

                if (notSame(category.getName())) {
                    categoryMapper.insert(category);
                } else {
                    throw new Exception("类别重名");
                }

            } else {
                if (notSame(category.getName())) {
                    categoryMapper.updateByPrimaryKey(category);
                } else {
                    throw new Exception("类别重名");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.fail();
        }

        return GetResult.success();
    }

    private boolean notSame(String name) {

        CategoryExample categoryE = new CategoryExample();
        categoryE.or().andNameEqualTo(name);
        List<Category> categories = categoryMapper.selectByExample(categoryE);
        if (categories.size() != 0) {
            return false;
        }
        return true;
    }

    @Override
    public Result deleteById(Integer categoryId) {

        try {
            /*找出要删除的类别下是否有商品*/
            CommodityCategoryExample commodityCategoryE = new CommodityCategoryExample();
            commodityCategoryE.or().andCategoryIdEqualTo(categoryId);
            List<CommodityCategory> commodityCategories = commodityCategoryMapper.selectByExample(commodityCategoryE);

            if (commodityCategories.size() == 0) {

                throw new Exception("要删除的类别，在其他商品中还在使用");
            }
            categoryMapper.deleteByPrimaryKey(categoryId);
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.fail();
        }
        return GetResult.success();
    }

    @Override
    public Category getOne(Integer categoryId) {
        return categoryMapper.selectByPrimaryKey(categoryId);
    }

    @Override
    public List<Category> getAll() {

        CategoryExample categoryE = new CategoryExample();
        categoryE.or().andIdIsNotNull();
        List<Category> categories = categoryMapper.selectByExample(categoryE);
        return categories;
    }
}
